package org.jgs1904.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 	文件上传工具类
 * 
 * @author junki
 * @date 2020年4月6日
 */
public class FileUploadUtil {

	private FileUploadUtil() {
	};

	public static Map<String, String[]> upload(HttpServletRequest request) {
		// 创建磁盘文件项工厂对象
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// 创建一个servlet文件上传类
		ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

		// 将请求参数转为文件项
		List<FileItem> fileItems = null;
		try {
			fileItems = servletFileUpload.parseRequest(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}

		// 创建一个map集合，用于保存实体属性
		Map<String, String[]> params = new HashMap<>();
		// 循环遍历所有文件项
		for (FileItem fileItem : fileItems) {
			// 判断文件项是否是普通表单字段
			if (fileItem.isFormField()) {
				try {
					params.put(fileItem.getFieldName(), new String[] { fileItem.getString("utf-8") });
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			} else {
				// 获取文件保存目录的真实路径
				String realPath = request.getServletContext().getRealPath("upload");

				// 创建今天的目录
				String dateDir = new SimpleDateFormat("yyyyMMdd").format(new Date());
				
				// 获取原文件名
				String realFileName = fileItem.getName();

				// 生成随机文件名
				String saveFileName = UUIDUtil.getUUID(16);
				// 判断原文件是否有后缀
				if (realFileName.contains(".")) {
					saveFileName += realFileName.substring(realFileName.indexOf("."));
				}

				// 保存文件到该路径
				new File(realPath + "/" + dateDir).mkdirs();
				try {
					fileItem.write(new File(realPath + "/" + dateDir + "/" + saveFileName));
				} catch (Exception e) {
					e.printStackTrace();
				}

				// 将文件路径保存到map集合
				params.put(fileItem.getFieldName(), new String[] { "upload/" + dateDir + "/" + saveFileName });

			}

		}
		
		return params;

	}

}
